<template>
	<view class="page page-bg page-withdrawal">
		<view class="page-body">
			<scroll-view class="scroll-view" :scroll-y="true">
				<view class="page-wrapper withdrawal-wrapper">
					<view class="page-form">
						<view class="form-item">
							<view class="item-label flex-between">
								<text>接收地址</text>
								<!-- <text class="btn-link">选择地址</text> -->
							</view>
							<view class="item-field">
								<input class="item-input" v-model="withdrawalForm.address" placeholder="输入或粘贴钱包地址" />
							</view>
						</view>
						<view class="form-item">
							<view class="item-label">转账数量</view>
							<view class="item-field">
								<view class="field-side">
									<view class="side-select" @click="selectPopupVisible = true">
										<view class="select-text">{{ currentToken }}</view>
										<image class="select-icon" src="../static/images/icon_downlist.png" />
									</view>
								</view>
								<input class="item-input" v-model="withdrawalForm.money" placeholder="输入提现数量"
									type="number" />
								<text v-show="isShowMoneyError" class="item-input-error">请输入数量</text>
							</view>
							<view class="item-field">
								<view class="field-meta">
									<view>
										<text
											v-if="currentToken == 'BNB'">实际到账：≈{{withdrawalForm.money? new BigNumber(withdrawalForm.money).minus(gasPrice).valueOf(): 0}}BNB</text>
										<text
											v-if="currentToken == 'USDT'">实际到账：≈{{withdrawalForm.money? amountFilter(new BigNumber(withdrawalForm.money).minus(1).valueOf()): 0}}USDT</text>
										<text
											v-if="currentToken == 'LK'">实际到账：≈{{withdrawalForm.money? amountFilter(new BigNumber(withdrawalForm.money).minus(1).valueOf()): 0}}LK</text>
									</view>
									<view>余额：{{
					                      amountFilter(getAssetBalance(currentToken))
					                    }}</view>
								</view>
							</view>
						</view>
						<view class="form-item">
							<view class="item-message">
								<view>网络费用: {{ gasPrice }} BNB</view>
							</view>
						</view>
						<view class="form-item">
							<button class="btn-primary border-round" @click="onConfirm">
								确认
							</button>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<u-popup v-model="selectPopupVisible" mode="bottom">
			<view class="popup-box">
				<view class="popup-header flex-between">
					<text>选择币种</text>
					<image class="popup-close" src="../static/images/icon/close@3x.png"
						@click="selectPopupVisible = false" />
				</view>
				<view class="box-body">
					<view class="option-list">
						<view class="list-item" v-for="(item, index) in selectOptions" :key="index"
							@click="changeSelectTo(item)">
							<view class="flex-between">
								<text class="item-name">{{ item }}</text>
								<image v-if="currentToken === item" class="item-check"
									src="../static/images/icon_success@3x.png" />
							</view>
							<text class="item-desc">{{ amountFilter(getAssetBalance(item)) }} {{ item }}</text>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup v-model="withdrawalVisible" mode="center" border-radius="14" width="720rpx" @close="handleCloseWallet">
			<view class="u-p-20 popup-box">
				<view>
					<view class="detail-info">
						<input type="password" v-model="passwordInput" placeholder="请输入钱包密码"
							style="border-radius: 16rpx;" class="border u-p-16 u-m-t-20 font-26" />
					</view>
					<button class="btn-primary" @click="handleWithdrawal">确定</button>
				</view>
				<view class="popup-header">
					<text>钱包密码</text>
					<view class="popup-close" @click="walletshow=false">
						<uni-icons type="closeempty" size="20"></uni-icons>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import BigNumber from "bignumber.js";
	import {
		mapGetters,
	} from 'vuex'
	import BLOCK_CONFIG from "@/config/block.js";
	import {
		ServerWalletApi
	} from "@/api/modules/ServerWallet.js"
	import {
		validateWalletPassword,
		decodePrivateKey
	} from "@/common/utils/utils.js"
	import {
		ethers
	} from "ethers";
	const {
		name,
	} = BLOCK_CONFIG.rpcInfo
	export default {
		data() {
			return {
				BigNumber,
				selectPopupVisible: false,
				isShowMoneyError: false,
				currentToken: "BNB",
				gasPrice: "0",
				withdrawalForm: {
					userId: "",
					money: "",
					address: "",
					code: "",
					pwd: "",
					blockName: "BNB",
				},
				selectOptions: ["BNB", "USDT", "LK"],
				Wallet_Assets: ["BNB", "USDT", "LK"],
				currentType: "USDT",
				assetList: [],
				walletAssetList: [],
				withdrawalVisible: false,
				passwordInput: ""
			}
		},
		computed: {
			...mapGetters({
				walletAddress: "user/getWalletAddress",
				walletPrivateKey: "user/getWalletPrivateKey",
				nftConfig: "user/getNftConfig"
			}),
		},
		onLoad(options) {
			const {
				token
			} = options
			token ? this.currentToken = token : null
		},
		mounted() {
			this.$nextTick(async () => {
				await this.getCurrentWalletBalance();
			})
		},
		methods: {
			async handleWithdrawal() {
				this.$ShowLoading()
				if (!this.passwordInput.trim()) return this.$HideLoading()
				const res = await validateWalletPassword(this.passwordInput)
				this.$HideLoading()
				if (res) {
					if (res.code == 1) {
						await this.onSubmit()
					} else {
						this.$Toast(res.msg)
					}
				}
			},
			async bnbSendTransaction() {
				let signer = null;
				if (this.walletPrivateKey) {
					const privateKey = await decodePrivateKey(this.walletPrivateKey)
					if (privateKey) {
						signer = new ethers.Wallet(privateKey);
					}
				}
				try {
					const result = await uni.request({
						url: this.nftConfig.rpcurl,
						method: 'POST',
						data: {
							jsonrpc: "2.0",
							method: "eth_getTransactionCount",
							params: [signer.address, "latest"],
							id: 1
						},
					})
					const nonce = Number(result[1].data.result)
					const gasPriceRes = await ServerWalletApi.getWalletGasPrice()
					const transaction = {
						gasPrice: ethers.parseUnits(gasPriceRes.data.gas_price_gwei, "gwei"),
						nonce,
						gasLimit: 1000000,
						to: this.withdrawalForm.address,
						value: ethers.parseEther(this.withdrawalForm.money),
						chainId: this.nftConfig.chain_id
					};
					const signedTx = await signer.signTransaction(transaction);
					const jsonRpcRequest = {
						jsonrpc: "2.0",
						method: "eth_sendRawTransaction",
						params: [signedTx],
						id: 1,
					};
					uni.request({
						url: this.nftConfig.rpcurl,
						method: 'POST',
						data: jsonRpcRequest,
						header: {
							'Content-Type': 'application/json',
						},
						success: (res) => {
							if (res.data.error) {
								uni.showToast({
									title: "交易失败",
									icon: "fail",
									duration: 2000,
								});
							} else {
								this.handleSuccess()
							}
						},
						fail: (err) => {
							uni.showToast({
								title: "网络错误",
								icon: "error",
								duration: 2000,
							});
						},
					});
				} catch (e) {
					uni.showToast({
						title: "网络错误",
						icon: "error",
						duration: 2000,
					});
				}
			},
			async othersSendTransaction() {
				let signer = null;
				if (this.walletPrivateKey) {
					const privateKey = await decodePrivateKey(this.walletPrivateKey)
					if (privateKey) {
						signer = new ethers.Wallet(privateKey);
						const item = this.nftConfig.tokens.find(item => item.name == this.currentToken)
						const contractInterface = new ethers.Interface(item.abi)
						const txData = contractInterface.encodeFunctionData('transfer', [this.withdrawalForm.address,
							ethers.parseEther(this.withdrawalForm.money)
						])
						const res = await uni.request({
							url: this.nftConfig.rpcurl,
							method: 'POST',
							data: {
								jsonrpc: "2.0",
								method: "eth_getTransactionCount",
								params: [signer.address, "latest"],
								id: 1
							},
						})
						const nonce = Number(res[1].data.result)
						const gasPriceRes = await ServerWalletApi.getWalletGasPrice()
						const tx = {
							nonce,
							gasPrice: ethers.parseUnits(gasPriceRes.data.gas_price_gwei, "gwei"),
							gasLimit: 1000000,
							to: item.contract,
							value: ethers.parseEther("0"),
							data: txData,
							chainId: this.nftConfig.chain_id
						}
						try {
							const signedTx = await signer.signTransaction(tx)
							const result = await uni.request({
								url: this.nftConfig.rpcurl,
								method: 'POST',
								data: {
									jsonrpc: "2.0",
									method: "eth_sendRawTransaction",
									params: [signedTx],
									id: 2
								},
							})
							if (result[1].statusCode == 200) {
								this.handleSuccess()
							} else {
								this.$Toast(result[1].errMsg)
							}
						} catch (e) {
							console.log(e)
						} finally {
							this.$HideLoading()
						}
					}
				}
			},
			handleSuccess() {
				uni.showToast({
					title: "成功",
					icon: "none",
					duration: 2000
				});
				this.withdrawalForm.money = "";
				this.withdrawalForm.address = "";
				this.withdrawalForm.code = "";
				this.withdrawalForm.pwd = "";
				setTimeout(() => {
					uni.navigateBack();
				}, 2000);
				this.withdrawalVisible = false;
			},
			getSendTransaction() {
				switch (this.currentToken) {
					case "BNB":
						this.bnbSendTransaction();
					case "USDT":
						this.othersSendTransaction();
					case "LK":
						this.othersSendTransaction();
					default:
						null;
				}
			},
			handleCloseWallet() {
				this.withdrawalVisible = false
			},
			async onSubmit() {
				this.$ShowLoading()
				await this.getSendTransaction();
			},
			onConfirm() {
				if (!this.withdrawalForm.address) {
					uni.showToast({
						title: "输入或粘贴钱包地址",
						icon: "none",
						duration: 2000
					});
					return;
				}
				if (!this.withdrawalForm.money) {
					uni.showToast({
						title: "输入提现数量",
						icon: "none",
						duration: 2000
					});
					return;
				}
				if (
					new BigNumber(this.gasPrice)
					.plus(this.getAssetBalance(this.currentToken))
					.lt(this.withdrawalForm.money)
				) {
					uni.showToast({
						title: "余额不足",
						icon: "none",
						duration: 2000,
					});
					return;
				}
				this.withdrawalVisible = true;
			},
			amountFilter(val) {
				if (val) {
					let valStr = val.toString();
					let dot = "";
					let integer = valStr;
					if (valStr.indexOf(".") > -1) {
						dot = valStr.substring(valStr.indexOf(".")).toString();
						integer = valStr.substring(0, valStr.indexOf("."));
					}
					// Handle negative numbers
					if (integer.startsWith("-")) {
						integer = "-" + integer.slice(1).replace(/(?!^)(?=(\d{3})+$)/g, ",");
					} else {
						integer = integer.replace(/(?!^)(?=(\d{3})+$)/g, ",");
					}
					return integer + dot;
				} else if (val === 0) {
					return val;
				} else {
					return "";
				}
			},
			async getCurrentWalletBalance() {
				try {
					if (!this.walletAddress) {
						this.walletAssetList = [];
						return;
					}
					const nftConfig = uni.getStorageSync('nftConfig')
					this.walletAssetList = nftConfig.tokens.map((item) => ({
						token: item.name,
						balance: "--",
						icon: item.icon,
						contract: item.contract
					}));
					const params = {
						address: this.walletAddress,
						token_contracts: nftConfig.tokens.map(item => item.contract).filter(item => item)
					}
					const res = await ServerWalletApi.getBalance(params)
					if (res.code == 0) {
						const apiData = res.data
						const updatedTokens = this.walletAssetList.map((item) => {
							if (item.token === "BNB") {
								item.balance = apiData.eth;
							} else {
								const balance = apiData.token_balances[item.contract];
								if (balance !== undefined) {
									item.balance = balance.toString();
								} else {
									item.balance = "0";
								}
							}
							return item;
						});
						this.walletAssetList = updatedTokens;
					}
				} catch (e) {
					uni.showToast({
						title: "获取余额失败",
						icon: "none",
						duration: 2000,
					});
				}
			},
			getAssetBalance(type) {
				return (
					this.walletAssetList.find((item) => item.token === type?.toUpperCase())
					?.balance || 0
				);
			},
			changeSelectTo(val) {
				this.currentToken = val
				this.withdrawalForm.blockName = val
				this.selectPopupVisible = false
				if (val === "USDT") {
					this.withdrawalForm.money = new BigNumber.max(1, this.withdrawalForm.money).valueOf();
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.page-withdrawal {
		/* #ifdef H5 */
		min-height: calc(100vh - var(--window-top));
		/* #endif */
		/* #ifndef H5 */
		min-height: 100vh;
		/* #endif */
		background-color: #fff;

		.page-form {
			.form-item {
				margin-top: 40rpx;

				&:first-child {
					margin-top: 0;
				}

				.btn-link {
					font-size: 28rpx;
					font-weight: 600;
					line-height: 44rpx;
					color: var(--mainColor);
				}

				.item-label {
					color: #333;
					font-size: 28rpx;
				}

				.item-field {
					margin-top: 20rpx;
					position: relative;

					.item-input {
						// background-color: var(--mainColor);
						background-color: #eee;
						border: 1px solid transparent;
						border-radius: 16rpx;
						color: #333;
						padding: 20rpx 32rpx;
						font-size: 28rpx;
					}

					.item-textarea {
						background-color: #0E0C12;
						border: 1px solid transparent;
						border-radius: 16rpx;
						color: $color-text-primary;
						padding: 20rpx 32rpx;
						font-size: 28rpx;
						width: 100%;
						box-sizing: border-box;
					}

					::v-deep .uni-input-placeholder,
					input::placeholder {
						color: rgba(#333, 0.4);
					}

					.field-meta {
						display: flex;
						justify-content: space-between;
						color: #333;
						font-size: 28rpx;

						view,
						text {
							display: flex;
							align-items: center;
						}
					}

					.field-side {
						display: flex;
						align-items: center;
						position: absolute;
						top: 0;
						right: 0;
						height: 100%;
						font-size: 28rpx;
						color: $color-text-primary;
						z-index: 1;

						.side-button {
							background: $color-primary;
							color: $color-text-primary;
							border-radius: 16rpx;
							padding: 8rpx 14rpx;
							font-size: 24rpx;
						}

						.side-select {
							position: relative;
							height: 100%;
							display: flex;
							justify-content: center;
							align-items: center;
							color: #333;

							.select-icon {
								width: 16rpx;
								height: 8rpx;
								padding: 0 30rpx 0 10rpx;
							}

							.select-text {
								padding: 0 15rpx 0 20rpx;
								text-align: center;
							}
						}
					}

					.icon-scanner {
						position: absolute;
						z-index: 1;
						width: 40rpx;
						height: 40rpx;
						right: 30rpx;
						top: 50%;
						transform: translateY(-50%);
					}
				}

				.item-message {
					background-color: #333;
					border-radius: 16rpx;
					color: #fff;
					// border: 1px solid #ff8819;
					font-size: 24rpx;
					padding: 30rpx;
					line-height: 1.5;
				}
			}
		}
	}

	::v-deep .option-popup {
		height: auto;
	}

	.option-popup {
		.popup-box {
			box-sizing: border-box;
			padding: 48rpx 32rpx;
			border-radius: 32rpx 32rpx 0rpx 0rpx;
			background: rgba(24, 17, 37, 1);
		}

		.popup-header {
			font-size: 32rpx;
			font-weight: 600;
			line-height: 48rpx;
			color: $color-text-primary;
			margin-bottom: 48rpx;

			.popup-close {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.box-header {
			padding: 30rpx 60rpx;
			border-bottom: 1px solid rgba($color-text-primary, 0.35);
			color: $color-text-primary;
			text-align: center;
		}

		.box-body {
			flex: 1;
			overflow-y: auto;

			.option-list {
				margin-top: 48rpx;

				.list-item {
					display: flex;
					flex-direction: column;
					padding: 12rpx;
					height: 86rpx;
					border-radius: 16rpx;
					border: 2rpx solid #1e1c21;

					&+.list-item {
						margin-top: 32rpx;
					}

					.item-name {
						flex: 1;
						font-family: PingFang SC;
						font-size: 30rpx;
						font-weight: 600;
						line-height: 48rpx;
						color: $color-text-primary;
					}

					.item-check {
						width: 36rpx;
						height: 36rpx;
					}

					.item-desc {
						// margin-top: 16rpx;
						font-family: Roboto;
						font-size: 28rpx;
						font-weight: 400;
						line-height: 44rpx;
						color: #78777a;
					}
				}
			}
		}
	}

	::v-deep .withdrawal-popup {
		height: auto;
		max-height: none;
	}

	.withdrawal-popup {
		.box-header {
			padding: 30rpx 60rpx;
			border-bottom: 1px solid rgba($color-text-primary, 0.35);
			color: $color-text-primary;
			text-align: center;
		}

		.withdrawal-list {
			padding: 20rpx 0;

			.list-item {
				display: flex;
				color: $color-text-primary;
				padding: 20rpx 40rpx;
				font-size: 28rpx;

				.item-field {
					flex: 1;
					text-align: right;
				}

				.item-tips {
					color: #ff8819;
					font-size: 24rpx;
				}
			}
		}

		.withdrawal-form {
			padding: 20rpx 40rpx;

			.form-item {
				position: relative;
				margin: 40rpx 0 0 0;

				&:first-child {
					margin-top: 0;
				}

				.item-input {
					background-color: #0E0C12;
					border: 1px solid transparent;
					border-radius: 16rpx;
					color: $color-text-primary;
					padding: 20rpx 32rpx;
					font-size: 28rpx;
				}

				::v-deep .uni-input-placeholder,
				input::placeholder {
					color: rgba($color-text-primary, 0.4);
				}

				.item-tips {
					margin-top: 30rpx;
					text-align: center;
					color: $color-text-primary;
					font-size: 28rpx;
				}

				.item-link {
					margin-left: 5rpx;
					color: #ff8819;
				}

				.valid-button {
					position: absolute;
					z-index: 1;
					top: 10rpx;
					right: 15rpx;
					display: inline-block;
					background: $color-primary;
					color: $color-text-primary;
					font-size: 24rpx;
				}
			}

			.form-button-group {
				display: flex;
				margin: 40rpx -10rpx 20rpx;

				.group-button {
					flex: 1;
					text-align: center;
					background: $color-text-primary;
					color: $color-primary;
					border-radius: 16rpx;
					font-size: 32rpx;
					padding: 20rpx;
					margin: 0 15rpx;

					&:last-child {
						color: $color-text-primary;
						background: $color-primary;
					}
				}
			}
		}
	}

	::v-deep .wallet-list-popup {
		height: auto;
		max-height: 80vh;
		overflow-y: auto;
	}

	.wallet-list-popup-content {
		box-sizing: border-box;
		padding: 48rpx 32rpx;
		border-radius: 32rpx 32rpx 0rpx 0rpx;
		background: rgba(24, 17, 37, 1);

		.popup-header {
			font-size: 32rpx;
			font-weight: 600;
			line-height: 48rpx;
			color: $color-text-primary;
			margin-bottom: 36rpx;

			.popup-close {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.bsc-add-box {
			padding: 32rpx;
			border-radius: 16rpx;
			border: 2rpx dashed #78777a;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.bsc-title {
				font-size: 32rpx;
				font-weight: 600;
				line-height: 48rpx;
				color: $color-text-primary;
			}

			.bsc-add {
				font-size: 28rpx;
				font-weight: 600;
				line-height: 44rpx;
				color: $color-primary;
			}
		}

		.wallet-list {
			.wallet-item {
				margin-top: 32rpx;
				padding: 32rpx;
				border-radius: 16rpx;
				border: 2rpx solid #1e1c21;
			}

			.item-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.item-row-group {
				display: inline-flex;
				align-items: center;
				column-gap: 16rpx;
			}

			.item-name {
				font-family: Inter;
				font-size: 32rpx;
				font-weight: 600;
				line-height: 48rpx;
				color: $color-text-primary;
			}

			.item-address {
				width: 500rpx;
				text-overflow: ellipsis;
				white-space: nowrap;
				overflow: hidden;
				font-family: Roboto;
				font-size: 28rpx;
				font-weight: 400;
				line-height: 44rpx;
				color: #78777a;
			}

			.item-asset {
				font-family: Roboto;
				font-size: 28rpx;
				font-weight: 600;
				line-height: 44rpx;
				text-align: right;
				color: #e6e6e7;
			}

			.icon-check {
				width: 40rpx;
				height: 40rpx;
			}

			.icon-copy {
				width: 24rpx;
				height: 24rpx;
			}
		}
	}

	.page-wrapper {
		padding: 1rem;
	}

	.btn-primary {
		background-color: var(--mainColor);
		font-size: 28rpx;
		color: #fff;
	}

	.flex-between {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	::v-deep .option-popup {
		height: auto;
	}

	.popup-box {
		box-sizing: border-box;
		padding: 52rpx 32rpx;
		border-radius: 32rpx 32rpx 0rpx 0rpx;
		// background: rgba(24, 17, 37, 1);
	}

	.popup-header {
		font-size: 32rpx;
		font-weight: 600;
		line-height: 48rpx;
		color: #333;
		margin-bottom: 36rpx;

		.popup-close {
			width: 40rpx;
			height: 40rpx;
		}
	}

	.box-header {
		padding: 30rpx 60rpx;
		border-bottom: 1px solid rgba(#fff, 0.35);
		color: #333;
		text-align: center;
	}

	.box-body {
		flex: 1;
		overflow-y: auto;

		.option-list {
			margin-top: 36rpx;

			.list-item {
				display: flex;
				flex-direction: column;
				padding: 12rpx;
				height: 120rpx;
				border-radius: 16rpx;
				border: 2rpx solid var(--mainColor);

				&+.list-item {
					margin-top: 32rpx;
				}

				.item-name {
					flex: 1;
					font-family: PingFang SC;
					font-size: 30rpx;
					font-weight: 600;
					line-height: 48rpx;
					color: var(--mainColor);
				}

				.item-check {
					width: 36rpx;
					height: 36rpx;
				}

				.item-desc {
					// margin-top: 16rpx;
					font-family: Roboto;
					font-size: 28rpx;
					font-weight: 400;
					line-height: 44rpx;
					color: #78777a;
				}
			}
		}
	}

	.popup-box {
		position: relative;
	}

	.popup-header {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;

		text {
			font-size: 28rpx;
		}

		.popup-close {
			position: absolute;
			top: 50%;
			right: 20rpx;
			transform: translateY(-50%);
		}
	}

	.btn-primary {
		font-size: 28rpx;
		color: #fff;
		background-color: var(--mainColor);
		margin-top: 80rpx;
	}

	.detail-info {
		margin-top: 40rpx;
		border-radius: 16rpx;
		padding: 40rpx;
	}

	.gray-bg {
		background: rgba(0, 0, 0, 0.02);
	}

	.item {
		margin-bottom: 40rpx;

		text {
			color: #333;
			font-size: 32rpx;
		}

		text:first-child {
			color: #999;
			font-size: 28rpx;
		}

		&:last-child {
			margin-bottom: 0;
		}
	}
</style>